package quit_all_group

import (
	"context"
	"fmt"
	log "github.com/sirupsen/logrus"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"mongofix/conf"
)

func getUserId(userId string) (int, int) {
	var result, tmp int
	fmt.Sscanf(userId, conf.ID_FROMAT_USER, &result, &tmp)
	return result, tmp
}
func getGroupId(groupId string) int {
	var result int
	fmt.Sscanf(groupId, conf.ID_FROMAT_GROUP, &result)
	return result
}

func Kick(ctx context.Context, groupId string, userId string) {
	groupIdNum := getGroupId(groupId)
	uid, _ := getUserId(userId)

	if groupIdNum <= 0 || uid <= 0 {
		log.Errorf("转换群ID或userId失败")
		return
	}

	groupCol := conf.GroupDao.Database("tia_comics_group").Collection(fmt.Sprintf("group_%d", groupIdNum%conf.Tia_group_col_num))
	one := groupCol.FindOne(ctx, bson.M{"_id": groupId})
	group := &Group{}
	err := one.Decode(group)
	if err != nil {
		log.Errorf("反序列化group失败，err:%v", err)
		return
	}
	log.Infof("群名称：%v", group.Name)

	if group.OwnerId == userId {
		log.Errorf("当前提出用户为群主，不能继续操作,groupId:%v,ownerId:%v,userId:%v", groupId, group.OwnerId, userId)
		return
	}

	col := conf.GroupDao.Database("tia_comics_usergroupop").Collection(fmt.Sprintf("user_group_op_%d", uid%conf.Tia_user_group_op_col_num))
	usergroupopResult := col.FindOne(ctx, bson.M{"uid": userId, "state": 1, "gid": groupId})

	usergroupop := &UserGroupOp{}
	err = usergroupopResult.Decode(usergroupop)
	if err != nil {
		log.Errorf("反序列化usergroupop失败，err:%v", err)
		return
	}
	exitGroup(ctx, usergroupop, groupCol, col, groupIdNum)

	log.Infof("用户%v从群%v中踢出", usergroupop.UId, usergroupop.GId)

}

func exitGroup(ctx context.Context, userGroupOp *UserGroupOp, groupCol *mongo.Collection, userGroupOpCol *mongo.Collection, groupIdInt int) {
	//退出群
	memberCol := conf.GroupDao.Database("tia_comics_groupmember").Collection(fmt.Sprintf("group_member_%d", groupIdInt%conf.Tia_group_member_col_num))
	delOne := memberCol.FindOneAndDelete(ctx, bson.M{"uid": userGroupOp.UId, "gid": userGroupOp.GId})
	if delOne == nil || delOne.Err() != nil {
		log.Errorf("删除群成员失败uid:%v,gid:%v", userGroupOp.UId, userGroupOp.GId)
	}
	log.Infof("删除群成员%v", userGroupOp.UId)

	//修改群成员数
	//$inc:{sequence_value:1}
	groupCol.UpdateOne(ctx, bson.M{"_id": userGroupOp.GId}, bson.M{"$inc": bson.M{"nums": -1}})

	log.Infof("修改群%v成员数量", userGroupOp.GId)
	//删除群加入记录
	userGroupOpCol.DeleteOne(ctx, bson.M{"id": userGroupOp.Id})
	log.Infof("删除入群记录userId:%v,groupID:%v", userGroupOp.UId, userGroupOp.GId)
}

func QuitAllGroup(ctx context.Context, userId string) {
	id, mid := getUserId(userId)

	if id <= 0 || mid <= 0 {
		log.Infof("id(%v)或者mid(%v)无效", id, mid)
		return
	}
	log.WithFields(log.Fields{"userIdStr": userId, "id": id}).Debug("获取拆分出的id为")

	col := conf.GroupDao.Database("tia_comics_usergroupop").Collection(fmt.Sprintf("user_group_op_%d", id%conf.Tia_user_group_op_col_num))

	//查询用户加入的所有的群
	result, err := col.Find(ctx, bson.M{"uid": userId, "state": 1})
	if err != nil {
		log.WithFields(log.Fields{"err": err, "userId": userId}).Error("查询用户加入的群失败")
		return
	}
	userGroupOpList := make([]*UserGroupOp, 0, 5)
	for result.Next(ctx) {
		tmp := &UserGroupOp{}
		err := result.Decode(tmp)
		if err != nil {
			log.Error("反序列化失败，err:", err)
			continue
		}
		userGroupOpList = append(userGroupOpList, tmp)
	}

	userCol := conf.UserDaos[mid%2].Database("tia_comics_user").Collection(fmt.Sprintf("user_%d", (mid/conf.Tia_user_db_num)%conf.Tia_user_col_num))

	one, err := userCol.UpdateOne(ctx, bson.M{"_id": userId}, bson.M{"$set": bson.M{"jgn": 0}})
	if err != nil {
		log.Errorf("修改用户信息失败:userId:%v", userId)
	}
	log.Infof("修改用户的加入群数量，修改条数：%v", one.ModifiedCount)

	for index, userGroupOp := range userGroupOpList {
		log.Infof("========处理第%v条数据，userId:%v，加入的群:%v,用户身份：%v", index, userGroupOp.UId, userGroupOp.GId, userGroupOp.Role)
		id := getGroupId(userGroupOp.GId)
		groupCol := conf.GroupDao.Database("tia_comics_group").Collection(fmt.Sprintf("group_%d", id%conf.Tia_group_col_num))
		one := groupCol.FindOne(ctx, bson.M{"_id": userGroupOp.GId})
		group := &Group{}
		err := one.Decode(group)
		if err != nil {
			log.Errorf("反序列化失败，err:%v", err)
			continue
		}
		log.Infof("群名称：%v", group.Name)

		if userGroupOp.Role == 60 {
			//检查群成员数量
			memberCol := conf.GroupDao.Database("tia_comics_groupmember").Collection(fmt.Sprintf("group_member_%d", id%conf.Tia_group_member_col_num))
			count, err := memberCol.CountDocuments(ctx, bson.M{"gid": userGroupOp.GId})
			if err != nil {
				log.Errorf("查询群成员数失败,gid:%v", userGroupOp.GId)
				continue
			}
			log.Infof("群:%v,的成员数量：%v", userGroupOp.GId, count)
			if count >= 2 {
				exitGroup(ctx, userGroupOp, groupCol, col, id)
				opts := options.Find()
				opts.SetSort(bson.D{{"ct", 1}})
				result, err := memberCol.Find(ctx, bson.M{"gid": userGroupOp.GId}, opts)
				if err != nil {
					log.Errorf("查询群候选群主失败,gid:%v,err:%v", userGroupOp.GId, err)
					continue
				}
				result.Next(ctx)
				tmpMember := &GroupMember{}
				err = result.Decode(tmpMember)
				if err != nil {
					log.Errorf("序列化群候选群主失败,gid:%v，err:%v", userGroupOp.GId, err)
					continue
				}
				//修改其他用户为群主
				memberCol.UpdateOne(ctx, bson.M{"id": tmpMember.Id}, bson.M{"$set": bson.M{"role": 60}})
				uid, _ := getUserId(tmpMember.UId)
				userGroupOpCol := conf.GroupDao.Database("tia_comics_usergroupop").Collection(fmt.Sprintf("user_group_op_%d", uid%conf.Tia_user_group_op_col_num))
				userGroupOpCol.UpdateOne(ctx, bson.M{"uid": tmpMember.UId, "gid": userGroupOp.GId}, bson.M{"$set": bson.M{"role": 60}})
				groupCol.UpdateOne(ctx, bson.M{"_id": userGroupOp.GId}, bson.M{"$set": bson.M{"oid": tmpMember.UId}})
				log.Infof("修改用户：%v,为群：%v的群主", tmpMember.UId, userGroupOp.GId)
			} else {
				exitGroup(ctx, userGroupOp, groupCol, col, id)
				//删除群信息
				groupCol.DeleteOne(ctx, bson.M{"_id": userGroupOp.GId})
				log.Infof("删除群：%v", userGroupOp.GId)
			}
		} else {
			exitGroup(ctx, userGroupOp, groupCol, col, id)
		}
	}
}
